//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package utils

import (
	"encoding/json"
	"strings"
)

func ConvertPromiseMsg(content string) string {
	obj := map[string]interface{}{}
	err := json.Unmarshal([]byte(content), &obj)
	if err != nil {
		return content
	}
	sb := &strings.Builder{}
	parseContentObj(sb, obj)
	return sb.String()
}

func parseContentObj(sb *strings.Builder, obj interface{}) {
	objList, ok := obj.([]interface{})
	if ok {
		for _, v := range objList {
			parseContentObj(sb, v)
		}
		return
	}
	objMap, ok := obj.(map[string]interface{})
	if ok {
		typeValue := ""
		textValue := ""
		for k, v := range objMap {
			if k == "type" {
				vStr, ok := v.(string)
				if ok {
					typeValue = vStr
				}
			} else if k == "text" {
				vStr, ok := v.(string)
				if ok {
					textValue = vStr
				}
			} else {
				parseContentObj(sb, v)
			}
		}
		if typeValue == "text" {
			sb.WriteString(textValue)
		}
	}
}
